﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static SmartWeigh.Controls.MonitorPanel;
using Newtonsoft.Json.Linq;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using SmartWeigh.Controls;
using SmartWeigh.ViewModel;
using DotNetSpeech;
using System.Windows.Threading;
using System.Threading;
using SmartWeighMonitor.Utils;
using System.Text.RegularExpressions;
using SmartWeighMonitor.ViewModel;
using Newtonsoft.Json;
using SmartWeighMonitor.Model;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;
using System.Net.Http;
using SmartWeighMonitor.Windows;
using System.IO;
using System.Net;
using MessageBox = System.Windows.Forms.MessageBox;

namespace SmartWeigh
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private MonitorViewModel viewModel;
        private MainViewModel mainViewModel;
        private SynchronizationContext _syncContext = null;
        private IModel channel = null;

        private delegate void MyDelegate(Object value);

        private ItemViewModel ItemViewModel;
        private SpVoice speech = new SpVoice();

        private DispatcherTimer timer;
        private String TextProperty1 = String.Empty;

        private String queryBillStatus = "0";

        public MainWindow()
        {
            InitializeComponent();
            /*   Bill bill = new Bill();
               bill.id = "12345678";
               PrintUtils.printWeighOrder(bill, "001");*/
            this.txtActTime.Text = DateTime.Now.ToString();

            mainViewModel = new MainViewModel();
            PoundList.DataContext = mainViewModel;
            _syncContext = SynchronizationContext.Current;

            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += new EventHandler(timeCycle);
            timer.Start();

            viewModel = new MonitorViewModel();
            viewModel.Item01 = new ItemViewModel();
            viewModel.Item02 = new ItemViewModel();

            String deviceCode = App.GetConfig().DeviceCode;
            String deviceName = App.GetConfig().DeviceName;
            String deviceType = App.GetConfig().DeviceType;

            String[] devices = deviceCode.Split(',');
            String[] deviceNames = deviceName.Split(',');
            String[] deviceTypes = deviceType.Split(',');

            if (devices.Length > 0)
            {
                viewModel.Item01.Id = devices[0];
                viewModel.Item01.DeviceName = deviceNames[0];
                viewModel.Item01.DeviceType = deviceTypes[0];
            }
            if (devices.Length > 1)
            {
                viewModel.Item02.Id = devices[1];
                viewModel.Item02.DeviceName = deviceNames[1];
                viewModel.Item02.DeviceType = deviceTypes[1];
            }
            String videoUrl01 = App.GetConfig().HikVideo_URL1;
            String videoUrl02 = App.GetConfig().HikVideo_URL2;
            viewModel.Item01.VideoUrl = videoUrl01;
            viewModel.Item02.VideoUrl = videoUrl02;

            this.DataContext = viewModel;

            var factory = new ConnectionFactory();//ConnectionFactory 是 RabbitMQ 客户端库中的一个类，用于创建到 RabbitMQ 服务器的连接。
            //你通过 ConnectionFactory 来配置连接的各个属性（如主机名、用户名、密码等），然后用它来创建连接。
            factory.HostName = App.GetConfig().Mq_HostName;//主机名，Rabbit会拿这个IP生成一个endpoint，这个很熟悉吧，就是socket绑定的那个终结点。
            factory.UserName = App.GetConfig().Mq_UserName;//默认用户名,用户可以在服务端自定义创建，有相关命令行
            factory.Password = App.GetConfig().Mq_Password;//默认密码
            if (!"".Equals(App.GetConfig().Mq_HostName))
            {
                var connection = factory.CreateConnection();//使用配置的参数创建到 RabbitMQ 服务器的连接。这个方法返回一个 IConnection 对象，表示与 RabbitMQ 服务器的连接。
                channel = connection.CreateModel();//通过连接对象创建一个 IModel 对象，表示一个通道（channel）。RabbitMQ 中的操作通常是在通道上进行的，例如发布、消费消息等。

                subscriptionMQ();//处理MQ中的消息
            }
            txtLoginUserName.Text = "操作员：" + App.getGlobalVariables().LoginUserName;

            if (!String.IsNullOrEmpty(viewModel.Item01.Id))
            {
                sendMonitorOperator(viewModel.Item01.Id);
                readClientAutoWeigh(viewModel.Item01.Id);
            }
            if (!String.IsNullOrEmpty(viewModel.Item02.Id))
            {
                sendMonitorOperator(viewModel.Item02.Id);
                readClientAutoWeigh(viewModel.Item02.Id);
            }

            this.Loaded += Window_Loaded;
        }

        public void MM_ReadCard(object sender, ReadCardEventArgs e)
        {
            MonitorPanel monitorPanel = (MonitorPanel)sender;

            JObject jsonObj = new JObject();
            jsonObj.Add("from", "monitor");
            jsonObj.Add("type", "ReadCard");

            sendClientMqMessage(monitorPanel.ItemData.Id, jsonObj);
        }

        public void MM_ReadWeight(object sender, ReadWeightEventArgs e)
        {
            MonitorPanel monitorPanel = (MonitorPanel)sender;

            JObject jsonObj = new JObject();
            jsonObj.Add("from", "monitor");
            jsonObj.Add("type", "ReadWeight");

            sendClientMqMessage(monitorPanel.ItemData.Id, jsonObj);
        }

        public void MM_SaveWeight(object sender, SaveWeightEventArgs e)
        {
            MonitorPanel monitorPanel = (MonitorPanel)sender;

            JObject jsonObj = new JObject();
            jsonObj.Add("from", "monitor");
            jsonObj.Add("type", "SaveWeight");

            sendClientMqMessage(monitorPanel.ItemData.Id, jsonObj);
        }

        private void sendClientMqMessage(String id, JObject jsonObj)
        {
            if (channel == null) return;
            var properties = channel.CreateBasicProperties();
            properties.DeliveryMode = 1;
            string message = jsonObj.ToString();
            channel.BasicPublish("", "Queue_" + id + "_Server", properties, Encoding.UTF8.GetBytes(message)); //生产消息
        }

        //允许过磅
        private void MM_ChangeWeighPermit(object sender, ChangeWeighPermitHandleEventArgs e)
        {
            MonitorPanel monitorPanel = (MonitorPanel)sender;
            string weighStatus = monitorPanel.ItemData.weighStatus;
            JObject paramJSON = new JObject();
            if ("allow".Equals(weighStatus))//改为不允许
            {
                weighStatus = "unAllow";
                monitorPanel.changeWeighStatus(weighStatus);//修改按钮名称

                JObject jsonObj1 = new JObject();
                jsonObj1.Add("from", "monitor");
                jsonObj1.Add("type", "ChangeWeigh");
                jsonObj1.Add("value", "notAllow");
                sendClientMqMessage(monitorPanel.ItemData.Id, jsonObj1);
                paramJSON.Add("Allow", "1");
            }
            else//改为允许
            {
                weighStatus = "allow";
                monitorPanel.changeWeighStatus(weighStatus);//修改按钮名称
                JObject jsonObj2 = new JObject();
                jsonObj2.Add("from", "monitor");
                jsonObj2.Add("type", "ChangeWeigh");
                jsonObj2.Add("value", "Allow");
                sendClientMqMessage(monitorPanel.ItemData.Id, jsonObj2);

                paramJSON.Add("Allow", "0");
            }
            String response = HttpPostHelper.doHttpPost("http://" + App.GetConfig().Nodered_Ip + ":" + App.GetConfig().Nodered_Port + "/PostMessage/AllowWeigh", paramJSON.ToString());
            JObject respJson = JObject.Parse(response);
        }

        //红外开关
        //绑定monitorPanel控件中的OnChangeLDOpenAndClose方法
        private void MM_ChangeLDOpenAndClose(object sender, ChangeLDOpenAndCloseEventArgs e)
        {
            MonitorPanel monitorPanel = (MonitorPanel)sender;
            string ldStatus = monitorPanel.ItemData.LDStatus;

            if ("open".Equals(ldStatus))
            {
                ldStatus = "close";
                monitorPanel.changeLdStatus(ldStatus);
                JObject jsonObj1 = new JObject();
                jsonObj1.Add("from", "monitor");
                //jsonObj1.Add("type", "ChangeLDOpen");
                jsonObj1.Add("type", "ChangeLDClose");
                sendClientMqMessage(monitorPanel.ItemData.Id, jsonObj1);
            }
            else
            {
                ldStatus = "open";
                monitorPanel.changeLdStatus(ldStatus);
                JObject jsonObj2 = new JObject();
                jsonObj2.Add("from", "monitor");
                //jsonObj2.Add("type", "ChangeLDClose");
                jsonObj2.Add("type", "ChangeLDOpen");
                sendClientMqMessage(monitorPanel.ItemData.Id, jsonObj2);
            }
        }

        public void MM_AutoWeighChange(object sender, AutoWeighEventArgs e)
        {
            MonitorPanel monitorPanel = (MonitorPanel)sender;
            string autoWeigh = monitorPanel.ItemData.AutoWeigh;

            if ("true".Equals(autoWeigh))
            {
                autoWeigh = "false";
                monitorPanel.changeAutoWeigh(autoWeigh);
            }
            else
            {
                autoWeigh = "true";
                monitorPanel.changeAutoWeigh(autoWeigh);
            }

            JObject jsonObj = new JObject();
            jsonObj.Add("from", "monitor");
            jsonObj.Add("type", "AutoWeigh");
            jsonObj.Add("value", autoWeigh);

            sendClientMqMessage(monitorPanel.ItemData.Id, jsonObj);
        }

        public void MM_ErrorDeal(object sender, ErrorDealEventArgs e)//处理报警
        {
            MonitorPanel monitorPanel = (MonitorPanel)sender;
            string clientId = monitorPanel.ItemData.Id;
            ItemViewModel itemViewModel = getMyItem(clientId);

            string billCode = itemViewModel.BillCode;
            string errorCode = "";
            if (viewModel.Item01.Id.Equals(itemViewModel.Id))
            {
                errorCode = viewModel.ErrorCode01;
            }
            else if (viewModel.Item02.Id.Equals(itemViewModel.Id))
            {
                errorCode = viewModel.ErrorCode02;
            }

            MessageBoxResult result = System.Windows.MessageBox.Show("是否解除该报警?", "确认", MessageBoxButton.YesNo);
            if (result != MessageBoxResult.Yes)//点击No
            {
                if (viewModel.Item01.Id.Equals(itemViewModel.Id))
                {
                    viewModel.ErrorMessage01 = "";
                    viewModel.ErrorCode01 = "";
                }
                else if (viewModel.Item02.Id.Equals(itemViewModel.Id))
                {
                    viewModel.ErrorMessage02 = "";
                    viewModel.ErrorCode02 = "";
                }
                JObject jsonObj1 = new JObject();
                jsonObj1.Add("from", "monitor");
                jsonObj1.Add("type", "AutoWeigh");
                jsonObj1.Add("value", "false");

                sendClientMqMessage(monitorPanel.ItemData.Id, jsonObj1);

                monitorPanel.changeAutoWeigh("false");
                return;
            }
            JObject resultJSON = uplaodErrorDeal(billCode, errorCode);
            string status = (string)resultJSON["result"];
            if (!"success".Equals(status))
            {
                string message = (string)resultJSON["message"];
                System.Windows.MessageBox.Show(message);
                return;
            }
            if (viewModel.Item01.Id.Equals(itemViewModel.Id))
            {
                viewModel.ErrorMessage01 = "";
                viewModel.ErrorCode01 = "";
            }
            else if (viewModel.Item02.Id.Equals(itemViewModel.Id))
            {
                viewModel.ErrorMessage02 = "";
                viewModel.ErrorCode02 = "";
            }

            JObject jsonObj = new JObject();
            //jsonObj.Add("from", "monitor");
            //jsonObj.Add("type", "AutoWeigh");
            //jsonObj.Add("value", "false");

            //sendClientMqMessage(monitorPanel.ItemData.Id, jsonObj);

            jsonObj = new JObject();
            jsonObj.Add("from", "monitor");
            jsonObj.Add("type", "DealError");
            jsonObj.Add("value", "");

            sendClientMqMessage(monitorPanel.ItemData.Id, jsonObj);

            //string autoWeigh = "false";
            //monitorPanel.changeAutoWeigh(autoWeigh);

            //JObject jsonObj1 = new JObject();
            //jsonObj1.Add("from", "monitor");
            //jsonObj1.Add("type", "ReadCard");

            //sendClientMqMessage(monitorPanel.ItemData.Id, jsonObj1);
            jsonObj = new JObject();
            jsonObj.Add("from", "monitor");
            jsonObj.Add("type", "SaveWeight");

            sendClientMqMessage(monitorPanel.ItemData.Id, jsonObj);
        }

        private void subscriptionMQ()
        {
            var consumer = new EventingBasicConsumer(channel);//创建消费者

            consumer.Received += (model, ea) =>//consumer.Received 是一个事件处理程序，当消费者接收到消息时会触发此事件。
            {
                try
                {
                    var body = ea.Body;//ea.Body 是消息的字节数据，Encoding.UTF8.GetString(body.ToArray()) 用于将字节数组转换为字符串（即消息内容）。
                    var message = Encoding.UTF8.GetString(body.ToArray());

                    JObject jsonObj = JObject.Parse(message);//JObject.Parse(message) 将消息解析为 JObject，这意味着消息内容是一个 JSON 格式的字符串。
                    string from = (string)jsonObj.GetValue("from");
                    channel.BasicAck(ea.DeliveryTag, multiple: false);//确认消息已被成功处理，并告知 RabbitMQ 消息可以从队列中移除。DeliveryTag 是每条消息的唯一标识符，用于消息确认。
                    if ("client".Equals(from))
                    {
                        ReceiveMsgEvent(jsonObj);
                    }
                }
                catch (Exception ex)
                {
                    //异常重试
                    //DeliveryTag: 唯一的编号
                    //requeue:如果 requeue 参数设置为 true，则 RabbitMQ 会重新将这条消息存入队列，以便发送给下一个订阅的消费者； 如果 requeue 参数设置为 false，则 RabbitMQ 立即会还把消息从队列中移除，而不会把它发送给新的消费者。
                    channel.BasicReject(ea.DeliveryTag, true);
                    //Console.WriteLine("处理收到的消息出错" + ex);
                }
            };
            if (null != viewModel.Item01.Id)
            {
                channel.BasicConsume("Queue_" + viewModel.Item01.Id + "_Client", false, consumer);//消费消息
            }
            if (null != viewModel.Item02.Id)
            {
                channel.BasicConsume("Queue_" + viewModel.Item02.Id + "_Client", false, consumer);//消费消息
            }
        }

        //private void subscriptionMQ()
        //{
        //    var consumer = new EventingBasicConsumer(channel);//消费者

        // if (null != viewModel.Item01.Id) { channel.BasicConsume("Queue_" + viewModel.Item01.Id +
        // "_Client", true, consumer);//消费消息 } if (null != viewModel.Item02.Id) {
        // channel.BasicConsume("Queue_" + viewModel.Item02.Id + "_Client", true, consumer);//消费消息 }
        // consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body.ToArray());

        //        JObject jsonObj = JObject.Parse(message);
        //        string from = (string)jsonObj.GetValue("from");
        //        if ("client".Equals(from))
        //        {
        //            ReceiveMsgEvent(jsonObj);
        //        }
        //    };
        //}

        private void ReceiveMsgEvent(Object obj)
        {
            MyDelegate d = new MyDelegate(DealMessage);
            this.Dispatcher.Invoke(d, obj);
        }

        private void DealMessage(Object obj)//处理type
        {
            JObject jsonObj = JObject.Parse(obj.ToString());
            String type = (String)jsonObj.GetValue("type");
            String clientId = (String)jsonObj.GetValue("clientId");

            if ("GetCarNo".Equals(type))
            {
                String carNo = (String)jsonObj.GetValue("carNo");

                ItemViewModel itemViewModel = getMyItem(clientId);
                if (null == itemViewModel) return;

                //clearViewModel(itemViewModel);

                itemViewModel.VideoCarNo = carNo;

                if (viewModel.Item01.Id.Equals(itemViewModel.Id))
                {
                    //monitorPanel01.showCar(true);
                }
                else if (viewModel.Item02.Id.Equals(itemViewModel.Id))
                {
                    //monitorPanel02.showCar(true);
                }
                String newCarNo = "";

                for (int i = 0; i < carNo.Length; i++)
                {
                    newCarNo += carNo.Substring(i, 1) + " ";
                }
                speak("车号:" + newCarNo + "请准备称重");
            }
            else if ("GetRFIDCarNo".Equals(type))
            {
                String carNo = (String)jsonObj.GetValue("carNo");

                ItemViewModel itemViewModel = getMyItem(clientId);
                if (null == itemViewModel) return;

                //clearViewModel(itemViewModel);

                itemViewModel.RFIDCarNo = carNo;
            }
            else if ("Weight".Equals(type))
            {
                String weight = (String)jsonObj.GetValue("weight");
                String steady = (String)jsonObj.GetValue("steady");

                ItemViewModel itemViewModel = getMyItem(clientId);
                if (null == itemViewModel) return;

                itemViewModel.Weight = weight;
                itemViewModel.Steady = steady;
                //monitorPanel01.changeWeightStatus(steady);
                if (viewModel.Item01.Id.Equals(itemViewModel.Id))
                {
                    monitorPanel01.changeWeightStatus(steady);
                }
                //else if (viewModel.Item02.Id.Equals(itemViewModel.Id))
                //{
                //    monitorPanel02.changeWeightStatus(steady);
                //}
            }
            else if ("PersonWeight".Equals(type))
            {
                String weight = (String)jsonObj.GetValue("weight");
                String steady = (String)jsonObj.GetValue("steady");

                ItemViewModel itemViewModel = getMyItem(clientId);
                if (null == itemViewModel) return;

                itemViewModel.PersonWeight = weight;
                itemViewModel.PersonSteady = steady;
            }
            else if ("VoiceAndLed".Equals(type))
            {
                String voiceMsg = (String)jsonObj.GetValue("voiceMsg");
                String ledMsg = (String)jsonObj.GetValue("ledMsg");

                ItemViewModel itemViewModel = getMyItem(clientId);
                if (null == itemViewModel) return;

                speak(voiceMsg);

                itemViewModel.VoiceText = voiceMsg;
                itemViewModel.LedText = ledMsg;
            }
            else if ("BillInfo".Equals(type))
            {
                JObject billObj = (JObject)jsonObj.GetValue("billObj");

                ItemViewModel itemViewModel = getMyItem(clientId);
                if (null == itemViewModel) return;
                itemViewModel.BillId = (String)billObj.GetValue("id");
                itemViewModel.BillCode = (String)billObj.GetValue("orderCode");
                itemViewModel.WeighType = (String)billObj.GetValue("weightStatus");
                itemViewModel.CarNo = (String)billObj.GetValue("carNo");
                itemViewModel.Product = (String)billObj.GetValue("materialName");
                itemViewModel.material = (String)billObj.GetValue("materialName");
                itemViewModel.JiHuaShu = (String)billObj.GetValue("planNum");
                itemViewModel.YuanFaJing = (String)billObj.GetValue("yuanfaNum");
                itemViewModel.ChaZhi = (String)billObj.GetValue("chazhi");
                itemViewModel.FaYouLiang = (String)billObj.GetValue("fayou");
                itemViewModel.PiZhong = (String)billObj.GetValue("pizhong");
                itemViewModel.MaoZhong = (String)billObj.GetValue("maozhong");
                itemViewModel.JingZhong = (String)billObj.GetValue("jingzhong");
                itemViewModel.QianBiaoShu = (String)billObj.GetValue("qianbiao");
                itemViewModel.HouBiaoShu = (String)billObj.GetValue("houbiao");
                itemViewModel.BusiType = (String)billObj.GetValue("busitype");
                itemViewModel.PersonWeight01 = (String)billObj.GetValue("personWeight01");
                itemViewModel.PersonWeight02 = (String)billObj.GetValue("personWeight02");
                itemViewModel.loadPlaceName = (String)billObj.GetValue("loadPlace");
                itemViewModel.customerName = (String)billObj.GetValue("customerName");
                itemViewModel.fnpolicemsg = (String)billObj.GetValue("fnpolicemsg");
                itemViewModel.waiPiWeight = (String)billObj.GetValue("waiPizhong");
                itemViewModel.waiMaoWeight = (String)billObj.GetValue("waiMaozhong");
                itemViewModel.waiNetWeight = (String)billObj.GetValue("waiJingzhong");
                itemViewModel.transName = (String)billObj.GetValue("transName");
                itemViewModel.portName = (String)billObj.GetValue("portName");
                itemViewModel.SaveStatus = "未保存";
                if (itemViewModel.MaoZhong != null)
                {
                    itemViewModel.grosschazi = ((Decimal)billObj.GetValue("maozhong") - (Decimal)billObj.GetValue("waiMaozhong")).ToString();
                }
                String image = (String)billObj.GetValue("billImage");
                if (image != null && image.Contains(","))
                {
                    string[] vs = image.Split(',');
                    image = vs[0];
                    if (image != null && image.Contains("www.qrhgstore.com"))
                    {
                        image.Replace("www.qrhgstore.com:8080", "192.168.23.20:8000");
                    }
                }
                else
                {
                    if (image != null && image.Contains("www.qrhgstore.com"))
                    {
                        image.Replace("www.qrhgstore.com:8080", "192.168.23.20:8000");
                    }
                }

                itemViewModel.billImage = image;
                //speak("刷卡成功");
            }
            else if ("gateStatus".Equals(type))
            {
                ItemViewModel itemViewModel = getMyItem(clientId);
                if (null == itemViewModel) return;

                String inOut = (String)jsonObj.GetValue("inOut");
                String open = (String)jsonObj.GetValue("open");

                if ("in".Equals(inOut))
                {
                    monitorPanel01.changeGateInStatus(open);
                }
                else if ("out".Equals(inOut))
                {
                    monitorPanel01.changeGateOutStatus(open);

                    if (open.Equals("1"))
                    {
                        clearViewModel(itemViewModel);
                        //monitorPanel01.showCar(false);
                    }
                }
            }
            else if ("LDStatus".Equals(type))
            {
                ItemViewModel itemViewModel = getMyItem(clientId);
                if (null == itemViewModel) return;
                String leftStatus = (String)jsonObj.GetValue("leftStatus");
                String rightStatus = (String)jsonObj.GetValue("rightStatus");
                if (viewModel.Item01.Id.Equals(itemViewModel.Id))
                {
                    monitorPanel01.changeLDLeftStatus(leftStatus);
                    monitorPanel01.changeLDRightStatus(rightStatus);
                }
                //else if (viewModel.Item02.Id.Equals(itemViewModel.Id))
                //{
                //    monitorPanel02.changeLDLeftStatus(leftStatus);
                //    monitorPanel02.changeLDRightStatus(rightStatus);
                //}
            }
            else if ("Complete".Equals(type))
            {
                ItemViewModel itemViewModel = getMyItem(clientId);
                if (null == itemViewModel) return;

                String message = (String)jsonObj.GetValue("message");
                String billId = (String)jsonObj.GetValue("billId");

                itemViewModel.SaveStatus = "保存完成";
                itemViewModel.VoiceText = message;
                itemViewModel.LedText = message;

                if (jsonObj.ContainsKey("pizhong"))
                {
                    itemViewModel.PiZhong = (String)jsonObj.GetValue("pizhong");
                }
                if (jsonObj.ContainsKey("maozhong"))
                {
                    itemViewModel.MaoZhong = (String)jsonObj.GetValue("maozhong");
                }
                if (jsonObj.ContainsKey("jingzhong"))
                {
                    itemViewModel.JingZhong = (String)jsonObj.GetValue("jingzhong");
                }

                speak("称重完成");
                App.getGlobalVariables().BillId = billId;
                //上传集控端屏幕截图
                _syncContext.Post(doUploadScreenPicture, billId);//itemViewModel.BillId
                _syncContext.Post(RefreshData, "");
                ItemViewModel = itemViewModel;
                //doUploadScreenPicture();
            }
            else if ("Error".Equals(type))//报警
            {
                ItemViewModel itemViewModel = getMyItem(clientId);
                if (null == itemViewModel) return;

                String message = (String)jsonObj.GetValue("message");
                String devalue = (String)jsonObj.GetValue("devalue");
                String maokui = (String)jsonObj.GetValue("maokui");//铅封出厂，二次进厂二次过磅为空
                String jingkui = (String)jsonObj.GetValue("jingkui"); //铅封出厂，二次进厂二次过磅，值为当前重量
                String cz = (String)jsonObj.GetValue("cz");
                // itemViewModel.BillId = (String)billObj.GetValue("id");
                /*  if (maokui!=null)
                  {
                      itemViewModel.grosschazi = maokui;
                  }
                  if (jingkui!=null)
                  {
                      itemViewModel.ChaZhi = jingkui;
                  }*/
                if (maokui != null)
                {
                    itemViewModel.grosschazi = maokui;
                    itemViewModel.ChaZhi = "";
                }
                if (maokui == null || maokui == "")
                {
                    if (jingkui != null) { itemViewModel.ChaZhi = jingkui; }
                }
                MatchCollection mc = Regex.Matches(message, @"([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1})");
                foreach (Match m in mc)
                {
                    string s = m.Groups[0].Value;

                    string x = "";

                    for (int i = 0; i < s.Length; i++)
                    {
                        x += s.Substring(i, 1) + " ";
                    }

                    message = message.Replace(s, x);
                }
                speak(message);
                if (cz == null)
                {
                    if (viewModel.Item01.Id.Equals(itemViewModel.Id))
                    {
                        viewModel.ErrorMessage01 = message;
                        viewModel.ErrorCode01 = devalue;
                    }
                    else if (viewModel.Item02.Id.Equals(itemViewModel.Id))
                    {
                        viewModel.ErrorMessage02 = message;
                        viewModel.ErrorCode02 = devalue;
                    }
                }
            }
            else if ("GetLoginUserInfo".Equals(type))
            {
                JObject jsonRespObj = new JObject();
                jsonRespObj.Add("from", "monitor");
                jsonRespObj.Add("type", "ServerOperatorInfo");
                jsonRespObj.Add("loginUserId", App.getGlobalVariables().LoginUserID);
                jsonRespObj.Add("loginUserName", App.getGlobalVariables().LoginUserName);

                sendClientMqMessage(clientId, jsonRespObj);
            }
            else if ("UploadClientAutoWeigh".Equals(type))
            {
                ItemViewModel itemViewModel = getMyItem(clientId);
                if (null == itemViewModel) return;
                String value = (String)jsonObj.GetValue("value");
                String ldStatus = (String)jsonObj.GetValue("ldStatus");
                String weighStatus = (String)jsonObj.GetValue("weighStatus");

                if (viewModel.Item01.Id.Equals(itemViewModel.Id))
                {
                    viewModel.Item01.AutoWeigh = value;
                    viewModel.Item01.LDStatus = ldStatus;
                    viewModel.Item01.weighStatus = weighStatus;
                    monitorPanel01.changeAutoWeigh(value);
                    monitorPanel01.changeLdStatus("open");
                    monitorPanel01.changeWeighStatus("allow");
                }
                //else if (viewModel.Item02.Id.Equals(itemViewModel.Id))
                //{
                //    viewModel.Item02.AutoWeigh = value;
                //    monitorPanel02.changeAutoWeigh(value);
                //}
            }
            else if ("ClearBillInfo".Equals(type))
            {
                ItemViewModel itemViewModel = getMyItem(clientId);
                if (null == itemViewModel) return;

                clearViewModel(itemViewModel);
                itemViewModel.VideoCarNo = "";
                //monitorPanel01.showCar(false);
            }
            else if ("uploadPic".Equals(type))
            {
                doUploadScreenPicture(App.getGlobalVariables().BillId);
                _syncContext.Post(uploadPic, "");
            }
            else if ("LeadSealing".Equals(type))
            {
                ItemViewModel itemViewModel = getMyItem(clientId);
                if (null == itemViewModel) return;
                InputQfNumWindow inputQfNumWindow = new InputQfNumWindow();
                inputQfNumWindow.setCarNo(itemViewModel.BillId);
                inputQfNumWindow.setMaterial(itemViewModel.Product);
                inputQfNumWindow.Owner = this;
                bool result = (bool)inputQfNumWindow.ShowDialog();
                string content = (string)inputQfNumWindow.Content;
                if (result)
                {
                    JObject json = new JObject();
                    json.Add("from", "monitor");
                    json.Add("type", "LeadSealing");
                    json.Add("leadSealing", content);
                    sendClientMqMessage(clientId, json);
                    System.Windows.MessageBox.Show("录入成功");
                }
            }
            else if ("InputPw1".Equals(type))
            {
                ItemViewModel itemViewModel = getMyItem(clientId);
                if (null == itemViewModel) return;
                String message = (String)jsonObj.GetValue("message");
                itemViewModel.fnpolicemsg = "司机选择蒸罐，请确认";
                PasswordWindow passwordWindow = new PasswordWindow();
                passwordWindow.setCarNumber(itemViewModel.CarNo);
                passwordWindow.setTips("选择蒸罐，确实后请输入密码");
                passwordWindow.Owner = this;
                bool result = (bool)passwordWindow.ShowDialog();

                //MessageBoxResult confirm = System.Windows.MessageBox.Show(message, "确认", MessageBoxButton.YesNo);
                //if (confirm != MessageBoxResult.Yes)
                if (!result)
                {
                    JObject json = new JObject();
                    json.Add("from", "monitor");
                    json.Add("type", "ProcessResult01");
                    json.Add("message", "fail");
                    sendClientMqMessage(clientId, json);
                    return;
                }
                else
                {
                    JObject json = new JObject();
                    json.Add("from", "monitor");
                    json.Add("type", "ProcessResult01");
                    json.Add("message", "success");
                    sendClientMqMessage(clientId, json);
                }
            }
            else if ("InputPw2".Equals(type))
            {
                ItemViewModel itemViewModel = getMyItem(clientId);
                if (null == itemViewModel) return;
                itemViewModel.fnpolicemsg = "司机选择打铅封出厂，请确认";
                PasswordWindow passwordWindow = new PasswordWindow();
                passwordWindow.setCarNumber(itemViewModel.CarNo);
                passwordWindow.setTips("选择铅封出厂，确认后请输入密码");
                passwordWindow.Owner = this;
                bool result = (bool)passwordWindow.ShowDialog();
                if (!result)
                {
                    JObject json = new JObject();
                    json.Add("from", "monitor");
                    json.Add("type", "ProcessResult02");
                    json.Add("message", "fail");
                    sendClientMqMessage(clientId, json);
                    return;
                }
                else
                {
                    JObject json = new JObject();
                    json.Add("from", "monitor");
                    json.Add("type", "ProcessResult02");
                    json.Add("message", "success");
                    sendClientMqMessage(clientId, json);
                    //InputQfNumWindow inputQfNumWindow = new InputQfNumWindow();
                    //inputQfNumWindow.setCarNo(itemViewModel.CarNo);
                    //inputQfNumWindow.setMaterial(itemViewModel.Product);
                    //inputQfNumWindow.Owner = this;
                    //bool inputResult = (bool)inputQfNumWindow.ShowDialog();

                    //if (inputResult)
                    //{
                    //    string content = (string)inputQfNumWindow.Content;
                    //    JObject newjson = new JObject();
                    //    newjson.Add("from", "monitor");
                    //    newjson.Add("type", "LeadSealing");
                    //    newjson.Add("leadSealing", content);
                    //    sendClientMqMessage(clientId, newjson);
                    //    System.Windows.MessageBox.Show("录入成功");

                    //}
                    //else
                    //{
                    //    System.Windows.MessageBox.Show("录入失败");

                    //}
                }
            }
            //else if ("ChangeWeigh".Equals(type))//允许过磅   0抬杆，1不抬杆
            //{
            //    String AllowType = (String)jsonObj.GetValue("value");
            //    JObject paramJSON = new JObject();

            // if ("notAllow".Equals(AllowType)) { paramJSON.Add("Allow", "1");

            //    }
            //    else if ("Allow".Equals(AllowType))
            //    {
            //        paramJSON.Add("Allow", "0");
            //    }
            //    String response = HttpPostHelper.doHttpPost("http://" + App.GetConfig().Nodered_Ip + ":" + App.GetConfig().Nodered_Port + "/PostMessage/AllowWeigh", paramJSON.ToString());
            //    JObject respJson = JObject.Parse(response);
            //}
            else if ("InputPw3".Equals(type))
            {
                ItemViewModel itemViewModel = getMyItem(clientId);
                if (null == itemViewModel) return;
                itemViewModel.fnpolicemsg = "司机选择扣除运费出厂，请确认";
                String message = (String)jsonObj.GetValue("message");
                PasswordWindow passwordWindow = new PasswordWindow();
                passwordWindow.setCarNumber(itemViewModel.CarNo);
                passwordWindow.setTips("选择扣除运费出厂，确认后请输入密码");
                passwordWindow.Owner = this;
                bool result = (bool)passwordWindow.ShowDialog();
                //MessageBoxResult confirm = System.Windows.MessageBox.Show(message, "确认", MessageBoxButton.YesNo);
                //if (confirm != MessageBoxResult.Yes)
                if (!result)
                {
                    JObject json = new JObject();
                    json.Add("from", "monitor");
                    json.Add("type", "ProcessResult03");
                    json.Add("message", "fail");
                    sendClientMqMessage(clientId, json);
                    return;
                }
                else
                {
                    JObject json = new JObject();
                    json.Add("from", "monitor");
                    json.Add("type", "ProcessResult03");
                    json.Add("message", "success");
                    sendClientMqMessage(clientId, json);
                }
            }
            else if ("AutoPrintBill".Equals(type))
            {
                String billId = (String)jsonObj.GetValue("billId");
                String positionCode = (String)jsonObj.GetValue("clientId");
                JObject json = new JObject();
                json.Add("billId", billId);
                json.Add("positionCode", positionCode);
                _syncContext.Post(printBill, json);
            }
        }

        private void printBill(object obj)
        {
            JObject jsonObj = (JObject)obj;
            String billId = (String)jsonObj.GetValue("billId");
            String positionCode = (String)jsonObj.GetValue("positionCode");

            JObject paramObject = new JObject();
            paramObject.Add("id", billId);
            Bill bill = new Bill();
            new Task(() =>
            {
                try
                {
                    String serverIp = App.GetConfig().HttpServerIp;
                    String serverPort = App.GetConfig().HttpServerPort;
                    String response = HttpPostHelper.doHttpPost("http://" + serverIp + ":" + serverPort + "/qd-s-factory/clientApi/queryDetail2", paramObject.ToString());
                    JObject rspJson = JObject.Parse(response);
                    string code = rspJson["code"].ToString();
                    if (code.ToLower() == "00000")
                    {
                        var jsonStr = rspJson["data"].ToString();
                        JObject jobj = JsonConvert.DeserializeObject<JObject>(jsonStr);
                        bill.carNo = (String)jobj.GetValue("carNumber");
                        bill.transName = (String)jobj.GetValue("transName");
                        bill.jingzhong = (String)jobj.GetValue("netWeight");
                        bill.pizhong = (String)jobj.GetValue("piWeight");
                        bill.maozhong = (String)jobj.GetValue("maoWeight");
                        bill.materialName = (String)jobj.GetValue("materialName");
                        bill.carName = (String)jobj.GetValue("carName");
                        bill.cmzPosition = (String)jobj.GetValue("cmzPosition");
                        bill.cpzPosition = (String)jobj.GetValue("cpzPosition");
                        bill.deficit = (String)jobj.GetValue("deficit");
                        bill.customerName = (String)jobj.GetValue("customerName");
                        bill.orderCode = (String)jobj.GetValue("billNo");
                        bill.cmzTime = (String)jobj.GetValue("cmzTime");
                        bill.cpzTime = (String)jobj.GetValue("cpzTime");
                        bill.outWaterMaoZhong = ((decimal)jobj.GetValue("maoWeight") - (decimal)jobj.GetValue("floatNum")).ToString();
                        string kuidun = ((decimal)jobj.GetValue("netWeight") - (decimal)jobj.GetValue("waiNetWeight")).ToString();
                        bill.floatNum = (String)jobj.GetValue("floatNum");
                        bill.oldFreightNum = (String)jobj.GetValue("oldFreightNum");
                        bill.freightNum = (String)jobj.GetValue("freightNum");
                        bill.carStatus = (String)jobj.GetValue("carStatus");
                        bill.msg = (String)jobj.GetValue("msg");
                        bill.companyName = (String)jobj.GetValue("companyName");
                        bill.moisture = (String)jobj.GetValue("moisture");

                        if (kuidun != "" && kuidun.Contains("-"))
                        {
                            bill.netLoss = kuidun;
                        }
                        else
                        {
                            bill.netLoss = "";
                        }
                        //JArray jArray = jobj.Value<JArray>("typeList");
                        //List<string> typeList = jArray.ToObject<List<string>>();
                        //string type = "";
                        ////List<String> list = typeList.Split(',').ToList();
                        //if (typeList.Contains("2"))
                        //{
                        //    type = "明水";
                        //}else if (typeList.Contains("3"))
                        //{
                        //    type = "回磅";
                        //}else if (typeList.Contains("41"))
                        //{
                        //    type = "蒸罐";
                        //}
                        if (bill.freightNum.Length == 3)
                        {
                            bill.delMethod = "打铅封";
                        }
                        else
                        {
                            bill.delMethod = "";
                        }
                        bill.id = billId;
                        PrintUtils.printWeighOrder(bill, positionCode);
                    }

                    //{
                    //    String serverIp = App.GetConfig().HttpServerIp;
                    //    String serverPort = App.GetConfig().HttpServerPort;
                    //    String response = HttpPostHelper.doHttpPost("http://" + serverIp + ":" + serverPort + "/ytBill/queryDetail2", paramObject.ToString());
                    //    JObject rspJson = JObject.Parse(response);
                    //    string code = rspJson["code"].ToString();
                    //    if (code.ToLower() == "200")
                    //    {
                    //        var jsonStr = rspJson["data"].ToString();
                    //        BillModel bill = JsonConvert.DeserializeObject<BillModel>(jsonStr);

                    // _syncContext.Post(doPrint, bill); }
                }
                catch (Exception ex)
                {
                }
            }).Start();
        }

        private void uploadPic(object obj)
        {
            String id = App.getGlobalVariables().BillId;
            String imageFilePath = App.getGlobalVariables().ImagePath;
            String url = "http://" + App.GetConfig().HttpServerIp + ":" + App.GetConfig().AuthHttpServerPort + "/guns/sysFileInfo/upload2";
            UploadImage(url, imageFilePath, id);
        }

        private void RefreshData(object obj)
        {
            LoadData();
        }

        private ItemViewModel getMyItem(String clientId)
        {
            if (clientId.Equals(viewModel.Item01.Id))
            {
                return viewModel.Item01;
            }
            else if (clientId.Equals(viewModel.Item02.Id))
            {
                return viewModel.Item02;
            }
            return null;
        }

        private void clearViewModel(ItemViewModel itemViewModel)
        {
            itemViewModel.CarNo = "";

            itemViewModel.LedText = "";
            itemViewModel.VoiceText = "";

            itemViewModel.BillCode = "";
            itemViewModel.WeighType = "";

            itemViewModel.Product = "";
            itemViewModel.JiHuaShu = "";

            itemViewModel.YuanFaJing = "";
            itemViewModel.ChaZhi = "";
            itemViewModel.FaYouLiang = "";
            itemViewModel.PiZhong = "";
            itemViewModel.MaoZhong = "";
            itemViewModel.JingZhong = "";
            itemViewModel.QianBiaoShu = "";
            itemViewModel.HouBiaoShu = "";
            itemViewModel.BusiType = "";

            itemViewModel.RFIDCarNo = "";
            itemViewModel.PersonWeight01 = "";
            itemViewModel.PersonWeight02 = "";

            itemViewModel.SaveStatus = "";
            itemViewModel.loadPlaceName = "";
            itemViewModel.fnpolicemsg = "";
            itemViewModel.customerName = "";
            itemViewModel.waiMaoWeight = "";
            itemViewModel.waiPiWeight = "";
            itemViewModel.waiNetWeight = "";
            itemViewModel.transName = "";
            itemViewModel.portName = "";
            itemViewModel.grosschazi = "";
            itemViewModel.billImage = "";
            if (viewModel.Item01.Id.Equals(itemViewModel.Id))
            {
                viewModel.ErrorMessage01 = "";
                viewModel.ErrorCode01 = "";
                //monitorPanel01.showCar(false);
            }
            else if (viewModel.Item02.Id.Equals(itemViewModel.Id))
            {
                viewModel.ErrorMessage02 = "";
                viewModel.ErrorCode02 = "";
                //monitorPanel02.showCar(false);
            }
        }

        private void speak(String message)
        {
            speech.Speak(" ", SpeechVoiceSpeakFlags.SVSFlagsAsync);
            if (null != message)
            {
                speech.Speak(message, SpeechVoiceSpeakFlags.SVSFlagsAsync);
            }
        }

        private void Button_Click_Text(object sender, RoutedEventArgs e)
        {
            speech.Speak(" ", SpeechVoiceSpeakFlags.SVSFlagsAsync);
            speech.Speak("1号磅,车号:鲁E00123,差值警报,请处理", SpeechVoiceSpeakFlags.SVSFlagsAsync);
        }

        public void timeCycle(object sender, EventArgs e)
        {
            new Thread(() =>
            {
                System.Windows.Application.Current.Dispatcher.BeginInvoke(
                    new Action(() =>
                    {
                        TextProperty1 = DateTime.Now.ToString();
                        this.txtActTime.Text = TextProperty1;
                    }));
            }).Start();
        }

        private void sendMonitorOperator(string clientId)
        {
            JObject jsonObj = new JObject();
            jsonObj.Add("from", "monitor");
            jsonObj.Add("type", "ServerOperatorInfo");
            jsonObj.Add("loginUserId", App.getGlobalVariables().LoginUserID);
            jsonObj.Add("loginUserName", App.getGlobalVariables().LoginUserName);

            sendClientMqMessage(clientId, jsonObj);
        }

        private void readClientAutoWeigh(string clientId)
        {
            JObject jsonObj = new JObject();
            jsonObj.Add("from", "monitor");
            jsonObj.Add("type", "UploadClientAutoWeigh");
            sendClientMqMessage(clientId, jsonObj);
        }

        private JObject uplaodErrorDeal(string billNo, string devalue, string password = "")
        {
            JObject resultJSON = new JObject();
            try
            {
                JObject paramObj = new JObject();
                paramObj.Add("devalue", devalue);
                paramObj.Add("billNo", billNo);
                paramObj.Add("password", password);
                paramObj.Add("code", App.getGlobalVariables().LoginUserID);
                paramObj.Add("name", App.getGlobalVariables().LoginUserName);
                String bodyJsonStr = paramObj.ToString();
                String serverIp = App.GetConfig().HttpServerIp;
                String serverPort = App.GetConfig().HttpServerPort;
                String result = HttpPostHelper.doHttpPost("http://" + serverIp + ":" + serverPort + "/qd-s-factory/ytCallPoliceLog/callHandle", bodyJsonStr);
                JObject resJSON = JObject.Parse(result);
                string status = (string)resJSON["status"];
                string message = (string)resJSON["message"];

                resultJSON.Add("result", status);
                resultJSON.Add("message", message);
            }
            catch (Exception ex)
            {
                resultJSON.Add("result", "fail");
                resultJSON.Add("message", "系统异常");
            }
            return resultJSON;
        }

        public void MM_ChangeClientDoorStatus(object sender, ChangeClientDoorStatusEventArgs e)
        {
            ItemViewModel itemData = e.Data;
            string inOut = e.InOut;
            string status = e.Status;

            JObject jsonObj = new JObject();
            jsonObj.Add("from", "monitor");
            jsonObj.Add("type", "ChangeDoorStatus");
            jsonObj.Add("inOut", inOut);
            jsonObj.Add("status", status);

            sendClientMqMessage(itemData.Id, jsonObj);
        }

        private void resetQueryParamaters()
        {
            queryBeginDate.SelectedDate = DateTime.Now;//.ToString("yyyy-MM-dd");
            queryEndDate.SelectedDate = DateTime.Now;//.ToString("yyyy-MM-dd");
            queryCarNo.Text = "";
        }

        private void doLoadData(Object s)
        {
            LoadData();
        }

        private void LoadData()
        {
            JObject paramObject = new JObject();
            if (!queryBeginDate.SelectedDate.ToString().Trim().Equals(""))
            {
                ;
                paramObject.Add("queryBeginDate", ((DateTime)queryBeginDate.SelectedDate).ToString("yyyy-MM-dd"));
            }
            if (!queryEndDate.SelectedDate.ToString().Trim().Equals(""))
            {
                paramObject.Add("queryEndDate", ((DateTime)queryEndDate.SelectedDate).ToString("yyyy-MM-dd"));
            }
            if (!queryCarNo.Text.ToString().Trim().Equals(""))
            {
                paramObject.Add("queryCarNo", queryCarNo.Text.ToString());
            }
            paramObject.Add("status", queryBillStatus);
            paramObject.Add("deviceCode", viewModel.Item01.Id);

            new Task(() =>
            {
                try
                {
                    String serverIp = App.GetConfig().HttpServerIp;
                    String serverPort = App.GetConfig().HttpServerPort;
                    String response = HttpPostHelper.doHttpPost("http://" + serverIp + ":" + serverPort + "/qd-s-factory/clientApi/queryBillsForWeight", paramObject.ToString());
                    JObject rspJson = JObject.Parse(response);
                    string code = rspJson["code"].ToString();
                    if (code.ToLower() == "00000")
                    {
                        var jsonStr = rspJson["data"].ToString();
                        List<BillModel> bills = JsonConvert.DeserializeObject<List<BillModel>>(jsonStr);

                        _syncContext.Post(SetDataList, bills);
                    }
                }
                catch (Exception ex)
                {
                }
            }).Start();
        }

        private void SetDataList(object obj)
        {
            mainViewModel.List.Clear();

            if (null == obj) return;
            List<BillModel> bills = (List<BillModel>)obj;

            foreach (BillModel bill in bills)
            {
                double qian = 0;
                double hou = 0;
                bill.chazhi = "0";
                if (bill.FySurfaceFront != null && bill.FySurfaceBack != null && bill.NetWeight != 0)
                {
                    qian = double.Parse(bill.FySurfaceFront);
                    hou = double.Parse(bill.FySurfaceBack);
                    bill.chazhi = (bill.NetWeight * 1000 - (hou - qian)).ToString("0.00");
                }

                mainViewModel.List.Add(bill);
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            resetQueryParamaters();
            LoadData();
        }

        private void button_click_queryReset(object sender, RoutedEventArgs e)
        {
            resetQueryParamaters();
        }

        private void radio_click_status(object sender, RoutedEventArgs e)
        {
            System.Windows.Controls.RadioButton button = (System.Windows.Controls.RadioButton)sender;
            string tag = (string)button.Tag;
            this.queryBillStatus = tag;
            LoadData();
        }

        private void Button_Click_Query(object sender, RoutedEventArgs e)
        {
            LoadData();
        }

        private void Button_Click_HisWeightLog(object sender, RoutedEventArgs e)//地磅曲线
        {
            HisWeight_Window hisWeightWindow = new HisWeight_Window();
            hisWeightWindow.Owner = this;
            BillModel bill = (BillModel)PoundList.SelectedItem;
            hisWeightWindow.setId(bill.juid);
            hisWeightWindow.ShowDialog();
        }

        private void button_click_TestScreenSave(object sender, RoutedEventArgs e)
        {
            BillModel bill = (BillModel)PoundList.SelectedItem;
            copyScreen(bill.Id);

            /*
            String baseImagePath = App.GetConfig().ImageSavePath;
            String today = DateTime.Now.ToString("yyyy-MM-dd");
            String path = baseImagePath + "/" + today;
            if (Directory.Exists(path) == false)
            {
                Directory.CreateDirectory(path);
            }

            int count = System.IO.Directory.GetFiles(path).Length;
            */
        }

        private void doUploadScreenPicture(Object id)
        {
            copyScreen((String)id);
        }

        [DllImport("gdi32.dll")]
        private static extern int BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, UInt32 dwRop);

        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateDC(string driver, string device, IntPtr res1, IntPtr res2);

        private void copyScreen(String id)
        {
            try
            {
                System.Drawing.Rectangle rect = new System.Drawing.Rectangle();
                rect.Width = Screen.PrimaryScreen.Bounds.Width;
                rect.Height = Screen.PrimaryScreen.Bounds.Height;
                IntPtr dcTmp = CreateDC("DISPLAY", "DISPLAY", (IntPtr)null, (IntPtr)null);
                //rect = Screen.GetWorkingArea(this);//获得当前屏幕的大小

                Graphics g = Graphics.FromHdc(dcTmp);

                //创建一个以当前屏幕为模板的图象
                System.Drawing.Image myimage = new Bitmap(rect.Width, rect.Height, g);

                //第二种得到全屏坐标的方法
                // Image myimage = new Bitmap(Screen.PrimaryScreen.Bounds.Width,Screen.PrimaryScreen.Bounds.Height,g);

                //创建以屏幕大小为标准的位图
                Graphics gg = Graphics.FromImage(myimage);

                IntPtr dc = g.GetHdc();//得到屏幕的DC
                IntPtr dcdc = gg.GetHdc();//得到Bitmap的DC
                BitBlt(dcdc, 0, 0, rect.Width, rect.Height, dc, 0, 0, 13369376);

                //调用此API函数，实现屏幕捕获

                g.ReleaseHdc(dc);//释放掉屏幕的DC
                gg.ReleaseHdc(dcdc);//释放掉Bitmap的DC
                                    //String imageFilePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + "temp.jpg";

                //存到本地，以时间生成文件
                //String baseImagePath = App.GetConfig().ImageSavePath;
                //String today = DateTime.Now.ToString("yyyy-MM-dd");
                //String path = baseImagePath + "/" + today + "/" + id +"/";
                //if (Directory.Exists(path) == false)
                //{
                //    Directory.CreateDirectory(path);
                //}

                //int count = System.IO.Directory.GetFiles(path).Length+1;
                //String fileName = count.ToString();

                //String imageFilePath = path + fileName + ".jpg";

                //myimage.Save(imageFilePath, ImageFormat.Jpeg);//以JPG文件格式来保存
                //myimage.Dispose();

                //生成临时图片文件
                String imageFilePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + "temp.jpg";
                myimage.Save(imageFilePath, ImageFormat.Jpeg);
                myimage.Dispose();

                App.getGlobalVariables().ImagePath = imageFilePath;
            }
            catch (Exception ex) { }
        }

        public void UploadImage(string uploadUrl, string imgPath, string id, string fileparameter = "file")
        {
            try
            {
                HttpWebRequest request = WebRequest.Create(uploadUrl) as HttpWebRequest;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ServicePoint.Expect100Continue = false;

                string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
                request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
                byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
                byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

                int pos = imgPath.LastIndexOf("/");
                string fileName = imgPath.Substring(pos + 1);

                //请求头部信息
                StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"" + fileparameter + "\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
                byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());

                FileStream fs = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
                byte[] bArr = new byte[fs.Length];
                fs.Read(bArr, 0, bArr.Length);
                fs.Close();

                Stream postStream = request.GetRequestStream();
                postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                postStream.Write(bArr, 0, bArr.Length);
                postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
                postStream.Close();

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                Stream instream = response.GetResponseStream();
                StreamReader sr = new StreamReader(instream, Encoding.UTF8);
                string content = sr.ReadToEnd();
                JObject rspJson = JObject.Parse(content);
                string code = rspJson["code"].ToString();
                if (code.Equals("00000"))
                {
                    JObject data = (JObject)rspJson.GetValue("data");
                    String filaName = (String)data.GetValue("fileObjectName");
                    doUpdateScreenPicture(filaName, id);
                }
            }
            catch (Exception ex) { }
        }

        private void uoloadPic(string path, String id)
        {
            try
            {
                var requestUri = "http://" + App.GetConfig().HttpServerIp + ":" + App.GetConfig().AuthHttpServerPort + "/guns/sysFileInfo/upload2";
                String response = HttpPostHelper.UploadFileApi(requestUri, path);
                JObject respJson = JObject.Parse(response);
                string status = respJson["success"].ToString();
                if (status.ToLower() == "true")
                {
                    String fileObjectName = respJson["data"]["fileObjectName"].ToString();
                    //System.Windows.MessageBox.Show(fileObjectName);

                    doUpdateScreenPicture(fileObjectName, id);

                    return;
                }
                /*
                HttpClient httpClient = new HttpClient();
                var content = new MultipartFormDataContent();
                content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(path)), "file", "temp.jpg");

                var requestUri = "http://" + App.GetConfig().HttpServerIp + ":" + App.GetConfig().AuthHttpServerPort + "/guns/sysFileInfo/upload2";
                String Authorization= App.getGlobalVariables().Authorization;
                httpClient.DefaultRequestHeaders.Add("Authorization", Authorization);

                //var result=httpClient.PostAsync(requestUri, content).Result;
                //if (result.IsSuccessStatusCode)
                //{
                //    account = await result.Content.ReadAsAsync<cuentaM>();
                //}
                String response = await httpClient.PostAsync(requestUri, content).Result.Content.ReadAsStringAsync();
                JObject respJson = JObject.Parse(response);
                string status = respJson["success"].ToString();
                if (status.ToLower() == "true")
                {
                    String fileObjectName = respJson["data"]["fileObjectName"].ToString();
                    //System.Windows.MessageBox.Show(fileObjectName);

                    doUpdateScreenPicture(fileObjectName,id);

                    return;
                }*/
            }
            catch (Exception ex) { }
        }

        private void doUpdateScreenPicture(String imagePath, String id)
        {
            JObject paramObject = new JObject();
            paramObject.Add("imagePath", imagePath);
            paramObject.Add("id", id);

            try
            {
                String serverIp = App.GetConfig().HttpServerIp;
                String serverPort = App.GetConfig().HttpServerPort;
                String response = HttpPostHelper.doHttpPost("http://" + serverIp + ":" + serverPort + "/qd-s-purchase/purchaseBill/updateBillWeightPicture", paramObject.ToString());
                JObject rspJson = JObject.Parse(response);
                string code = rspJson["code"].ToString();
                if (code.ToLower() == "00000")
                {
                    _syncContext.Post(doLoadData, "");
                }
            }
            catch (Exception ex) { }
        }

        private void Button_Click_OneImage(object sender, RoutedEventArgs e)
        {
            BillModel bill = (BillModel)PoundList.SelectedItem;
            try
            {
                System.Diagnostics.Process.Start(App.GetConfig().ImagePath + bill.tareOneImg);
            }
            catch (Exception ex) { }
        }

        private void Button_Click_TwoImage(object sender, RoutedEventArgs e)
        {
            BillModel bill = (BillModel)PoundList.SelectedItem;
            try
            {
                System.Diagnostics.Process.Start(App.GetConfig().ImagePath + bill.tareTwoImg);
            }
            catch (Exception ex) { }
        }

        private void Button_Click_ReturnCard(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result = System.Windows.MessageBox.Show("是否退卡?", "确认", MessageBoxButton.YesNo);
            if (result != MessageBoxResult.Yes)
            {
                return;
            }

            JObject jsonObj = new JObject();
            jsonObj.Add("from", "monitor");
            jsonObj.Add("type", "ReturnCard");
            sendClientMqMessage(viewModel.Item01.Id, jsonObj);
        }

        private void Button_Click_ClearBillInfo(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result = System.Windows.MessageBox.Show("是否清除称重数据?", "确认", MessageBoxButton.YesNo);
            if (result != MessageBoxResult.Yes)
            {
                return;
            }
            JObject jsonObj = new JObject();
            jsonObj.Add("from", "monitor");
            jsonObj.Add("type", "WorkComplete");
            sendClientMqMessage(viewModel.Item01.Id, jsonObj);
        }

        private void Button_Click_PrintWeighOrder(object sender, RoutedEventArgs e)//打印榜单
        {
            BillModel bill = (BillModel)PoundList.SelectedItem;
            JObject jsonObj = new JObject();
            jsonObj.Add("from", "monitor");
            jsonObj.Add("type", "printWeighOrder");
            jsonObj.Add("billobj", JObject.FromObject(bill));
            sendClientMqMessage(viewModel.Item01.Id, jsonObj);
        }

        private void Button_Click_ReWeigh(object sender, RoutedEventArgs e)//复磅
        {
            MessageBoxResult result = System.Windows.MessageBox.Show("是否选择复磅?", "确认", MessageBoxButton.YesNo);
            if (result != MessageBoxResult.Yes)
            {
                return;
            }
            String serverIp = App.GetConfig().HttpServerIp;
            String serverPort = App.GetConfig().HttpServerPort;
            BillModel bill = (BillModel)PoundList.SelectedItem;
            JObject json = new JObject();
            json.Add("id", bill.Id);
            String response = HttpPostHelper.doHttpPost("http://" + serverIp + ":" + serverPort + "/qd-s-factory/clientApi/fubang", json.ToString());
            JObject rspJson = JObject.Parse(response);
            string code = rspJson["code"].ToString();
            if (code.ToLower() == "00000")
            {
                JObject jsonObj = new JObject();
                jsonObj.Add("from", "monitor");
                jsonObj.Add("type", "reWeigh");
                sendClientMqMessage(viewModel.Item01.Id, jsonObj);
                MessageBox.Show("复磅成功");
                LoadData();
            }
        }

        private void Button_Click_QueryRecord(object sender, RoutedEventArgs e)
        {
            RecordWindow recordWindow = new RecordWindow(this);
            recordWindow.setDeviceCode(viewModel.Item01.Id);
            recordWindow.Owner = this;
            recordWindow.Show();
        }

        //private void Button_Click_SteamTank(object sender, RoutedEventArgs e)
        //{
        //    MessageBoxResult result = System.Windows.MessageBox.Show("是否选择蒸罐?", "确认", MessageBoxButton.YesNo);
        //    if (result != MessageBoxResult.Yes)
        //    {
        //        return;
        //    }
        //    JObject jsonObj = new JObject();
        //    jsonObj.Add("from", "monitor");
        //    jsonObj.Add("type", "SteamTank");
        //    sendClientMqMessage(viewModel.Item01.Id, jsonObj);
        //}

        //private void Button_Click_LeadSealing(object sender, RoutedEventArgs e)
        //{
        //    JObject jsonObj = new JObject();
        //    jsonObj.Add("from", "monitor");
        //    jsonObj.Add("type", "LeadSealing");
        //    sendClientMqMessage(viewModel.Item01.Id, jsonObj);
        //    AddFreightWindow addFreightWindow = new AddFreightWindow(ItemViewModel);
        //    addFreightWindow.Owner=this;
        //    addFreightWindow.ShowDialog();
        //}

        //private void Button_Click_DeductionFreight(object sender, RoutedEventArgs e)
        //{
        //    JObject jsonObj = new JObject();
        //    jsonObj.Add("from", "monitor");
        //    jsonObj.Add("type", "DeductionFreight");
        //    sendClientMqMessage(viewModel.Item01.Id, jsonObj);
        //    JObject paramJSON = new JObject();
        //    paramJSON.Add("id", ItemViewModel.BillId);
        //    paramJSON.Add("clfs", "3");
        //    String response = HttpPostHelper.doHttpPost("/qd-s-factory/clientApi/tareByGuid", paramJSON.ToString());
        //    JObject respJson = JObject.Parse(response);
        //    if (!respJson.ContainsKey("success"))
        //    {
        //        System.Windows.MessageBox.Show("发生异常");
        //        return;
        //    }
        //    string status = respJson["success"].ToString();
        //    if (status.ToLower() != "true")
        //    {
        //        System.Windows.MessageBox.Show(respJson["message"].ToString());
        //        return;
        //    }
        //    System.Windows.MessageBox.Show("录入成功");
        //}
        public void rePrint(BillModel bill)
        {
            JObject jsonObj = new JObject();
            jsonObj.Add("from", "monitor");
            jsonObj.Add("type", "printWeighOrder");
            jsonObj.Add("billObj", JObject.FromObject(bill));
            sendClientMqMessage(App.GetConfig().DeviceCode, jsonObj);
        }

        private void MM_ChangeLDOpen(object sender, ChangeLDOpenEventArgs e)
        {
            MonitorPanel monitorPanel = (MonitorPanel)sender;

            JObject jsonObj = new JObject();
            jsonObj.Add("from", "monitor");
            jsonObj.Add("type", "ChangeLDOpen");
            sendClientMqMessage(monitorPanel.ItemData.Id, jsonObj);
        }

        private void MM_ChangeLDClose(object sender, ChangeLDCloseEventArgs e)
        {
            MonitorPanel monitorPanel = (MonitorPanel)sender;

            JObject jsonObj = new JObject();
            jsonObj.Add("from", "monitor");
            jsonObj.Add("type", "ChangeLDClose");
            sendClientMqMessage(monitorPanel.ItemData.Id, jsonObj);
        }

        private void test(object sender, RoutedEventArgs e)
        {
            printBill("1703969112321531906");
        }
    }
}